package com.dynamic.mybatis.core.serialization;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dynamic.mybatis.core.datasource.DataSourceProperty;
import com.dynamic.mybatis.core.enums.Constants;
import com.dynamic.mybatis.core.intercept.DynamicDataSourceHandler;
import com.dynamic.mybatis.core.serialization.entity.DataSourceEntity;
import com.dynamic.mybatis.core.serialization.entity.MappedStatementEntity;
import com.dynamic.mybatis.core.serialization.mapper.DataSourceMapper;
import com.dynamic.mybatis.core.session.DynamicSqlSessionTemplate;
import com.dynamic.mybatis.core.utils.CollectionUtils;
import com.dynamic.mybatis.core.utils.StringUtils;

import javax.sql.DataSource;
import java.util.List;
import java.util.Map;

/**
 * @Description
 * @Author xs
 * @Date 2023/5/23 13:28
 */

public class DataSourcePersistenceHandler implements DynamicDataSourceHandler {
    private DataSourceMapper dataSourceMapper;

    public DataSourcePersistenceHandler(DataSourceMapper dataSourceMapper) {
        this.dataSourceMapper = dataSourceMapper;
    }

    @Override
    public void before(OPERATE operate, Object dataSourceKey, DataSource dataSource, DataSourceProperty property, Map<Object, Object> attributes) {
        System.err.println("before dataSource handle.   " + operate + "   " + dataSourceKey);
    }

    @Override
    public void after(OPERATE operate, Object dataSourceKey, DataSource dataSource, DataSourceProperty property, Map<Object, Object> attributes) {
        System.err.println("after dataSource handle.   " + operate + "   " + dataSourceKey);
        Map<String, Object> data = JSON.parseObject(JSON.toJSONString(property));
        if (StringUtils.isNotBlank(property.getUid())) {
            data.put("id", Integer.valueOf(property.getUid()));
        }
        DataSourceEntity dataSourceEntity = new DataSourceEntity();
        LambdaQueryWrapper<DataSourceEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DataSourceEntity::getTenantCode,dataSourceEntity.getTenantCode());
        wrapper.eq(DataSourceEntity::getCode,dataSourceEntity.getCode());
        wrapper.eq(DataSourceEntity::getIsDeleted, 0);
        List<DataSourceEntity> list = dataSourceMapper.selectList(wrapper);
        if(CollectionUtils.isNotEmpty(list)){
            dataSourceEntity.setId(list.get(0).getId());
            dataSourceMapper.updateById(dataSourceEntity);
        }else {
            dataSourceMapper.insert(dataSourceEntity);
        }
    }
}